<?php
/**
 * Created by PhpStorm.
 * User: dy
 * Date: 2019/12/27
 * Time: 9:04
 */
namespace util;
class ArrayUtil
{
    protected static $instance = null;
    private function __construct()
    {
    }
    private function __clone()
    {
    }

    public static function instance(){
        if(empty(self::$instance)){
            self::$instance = new static();
        }
        return self::$instance;
    }
    /**
     * 数组转换为字符串，主要用于把分隔符调整到第二个参数
     * @param  array  $arr  要连接的数组
     * @param  string $glue 分割符
     * @return string
     */
    function arrToStr(array $arr,string $glue = ','):string
    {
        return implode($glue, $arr);
    }

    /**
     * 将二维数组数组按某个键提取出来组成新的索引数组
     */
    function array_extract($array = [], $key = 'id')
    {
        $count = count($array);
        $new_arr = [];
        for($i = 0; $i < $count; $i++) {
            if (!empty($array) && !empty($array[$i][$key])) {
                $new_arr[] = $array[$i][$key];
            }
        }
        return $new_arr;
    }

    /**
     * 根据某个字段获取关联数组
     */
    function array_extract_map($array = [], $key = 'id'){
        $count = count($array);
        $new_arr = [];
        for($i = 0; $i < $count; $i++) {
            $new_arr[$array[$i][$key]] = $array[$i];
        }
        return $new_arr;
    }

    /**
     * 关联数组转索引数组
     */
    function relevance_arr_to_index_arr($array)
    {
        $new_array = [];

        foreach ($array as $v)
        {
            $temp_array = [];
            foreach ($v as $vv)
            {
                $temp_array[] = $vv;
            }
            $new_array[] = $temp_array;
        }
        return $new_array;
    }
}